package com.bootx.service.impl;

import com.bootx.service.RedisService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RList;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author black
 */
@Service
public class RedisServiceImpl implements RedisService {

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void setString(String key, String value) {
        redissonClient.getBucket(key).set(value);
    }

    @Override
    public String getString(String key) {
        Object value = redissonClient.getBucket(key).get();
        return value != null ? value.toString() : null;
    }

    @Override
    public void deleteString(String key) {
        redissonClient.getBucket(key).delete();
    }

    @Override
    public void setNumber(String key, long value) {
        RAtomicLong atomicLong = redissonClient.getAtomicLong(key);
        atomicLong.set(value);
    }

    @Override
    public long getNumber(String key) {
        RAtomicLong atomicLong = redissonClient.getAtomicLong(key);
        return atomicLong.get();
    }

    @Override
    public long increment(String key, long delta) {
        RAtomicLong atomicLong = redissonClient.getAtomicLong(key);
        return atomicLong.addAndGet(delta);
    }

    @Override
    public void deleteNumber(String key) {
        RAtomicLong atomicLong = redissonClient.getAtomicLong(key);
        atomicLong.delete();
    }

    @Override
    public <T> void addToList(String key, T value) {
        RList<String> list = redissonClient.getList(key);
        try {
            list.add(objectMapper.writeValueAsString(value));
        } catch (JsonProcessingException e) {
            throw new RuntimeException("序列化失败", e);
        }
    }

    @Override
    public <T> void addAllToList(String key, List<T> values) {
        RList<String> list = redissonClient.getList(key);
        List<String> jsonList = new ArrayList<>();
        for (T value : values) {
            try {
                jsonList.add(objectMapper.writeValueAsString(value));
            } catch (JsonProcessingException e) {
                throw new RuntimeException("序列化失败", e);
            }
        }
        list.addAll(jsonList);
    }

    @Override
    public <T> List<T> getList(String key, int startIndex, int count, Class<T> clazz) {
        RList<String> list = redissonClient.getList(key);
        int size = list.size();
        if (size == 0 || startIndex >= size) {
            return new ArrayList<>();
        }
        int endIndex = Math.min(startIndex + count, size);
        List<String> sublist = list.subList(startIndex, endIndex);

        List<T> result = new ArrayList<>();
        for (String json : sublist) {
            try {
                result.add(objectMapper.readValue(json, clazz));
            } catch (JsonProcessingException e) {
                throw new RuntimeException("反序列化失败", e);
            }
        }
        return result;
    }

    @Override
    public <T> List<T> getListFromEnd(String key, int count, Class<T> clazz) {
        RList<String> list = redissonClient.getList(key);
        int size = list.size();
        if (size == 0) {
            return new ArrayList<>();
        }

        int startIndex = Math.max(size - count, 0);
        List<String> sublist = list.subList(startIndex, size);

        List<T> result = new ArrayList<>();
        for (int i = sublist.size() - 1; i >= 0; i--) {
            String json = sublist.get(i);
            try {
                result.add(objectMapper.readValue(json, clazz));
            } catch (JsonProcessingException e) {
                throw new RuntimeException("反序列化失败", e);
            }
        }
        return result;
    }

    @Override
    public <T> void updateListAtIndex(String key, int index, T value) {
        RList<String> list = redissonClient.getList(key);
        if (index >= 0 && index < list.size()) {
            try {
                list.set(index, objectMapper.writeValueAsString(value));
            } catch (JsonProcessingException e) {
                throw new RuntimeException("序列化失败", e);
            }
        }
    }

    @Override
    public void removeFromList(String key, Object value) {
        RList<String> list = redissonClient.getList(key);
        try {
            String json = objectMapper.writeValueAsString(value);
            list.remove(json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("序列化失败", e);
        }
    }

    @Override
    public void removeFromListByIndex(String key, int index) {
        RList<String> list = redissonClient.getList(key);
        if (index >= 0 && index < list.size()) {
            list.remove(index);
        }
    }

    @Override
    public <K, V> void putMapValue(String key, K mapKey, V mapValue) {
        RMap<K, String> map = redissonClient.getMap(key);
        try {
            map.put(mapKey, objectMapper.writeValueAsString(mapValue));
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Map序列化失败", e);
        }
    }

    @Override
    public <K, V> void putAllMap(String key, Map<K, V> mapData) {
        RMap<K, String> map = redissonClient.getMap(key);
        mapData.forEach((k, v) -> {
            try {
                map.put(k, objectMapper.writeValueAsString(v));
            } catch (JsonProcessingException e) {
                throw new RuntimeException("Map序列化失败", e);
            }
        });
    }

    @Override
    public <V> V getMapValue(String key, Object mapKey, Class<V> clazz) {
        RMap<Object, String> map = redissonClient.getMap(key);
        String json = map.get(mapKey);
        if (json == null) return null;
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Map反序列化失败", e);
        }
    }

    @Override
    public <K, V> Map<K, V> getAllMap(String key, Class<K> keyClass, Class<V> valueClass) {
        RMap<K, String> map = redissonClient.getMap(key);
        Map<K, V> result = new java.util.HashMap<>();
        map.forEach((k, vJson) -> {
            try {
                result.put(k, objectMapper.readValue(vJson, valueClass));
            } catch (JsonProcessingException e) {
                throw new RuntimeException("Map反序列化失败", e);
            }
        });
        return result;
    }

    @Override
    public void removeMapKey(String key, Object mapKey) {
        RMap<Object, Object> map = redissonClient.getMap(key);
        map.remove(mapKey);
    }

    @Override
    public void clearMap(String key) {
        RMap<Object, Object> map = redissonClient.getMap(key);
        map.clear();
    }

    @Override
    public Long increment(String key) {
        RAtomicLong atomicLong = redissonClient.getAtomicLong(key);
        return atomicLong.addAndGet(1);
    }


    @Override
    public void clearList(String key) {
        redissonClient.getList(key).clear();
    }

    @Override
    public void delete(String key) {
        redissonClient.getBucket(key).delete();
    }

    @Override
    public Boolean hasKey(String key) {
        return redissonClient.getBucket(key).isExists();
    }
}
